package com.gz.config;

import com.gz.handler.interceptor.JwtInterceptor;
import com.gz.handler.interceptor.UrlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
//开启配置项自动读取填充到对象属性中，且填充后的对象自动加入IoC容器
@EnableConfigurationProperties(UrlProperties.class)
@Slf4j
public class BookMvcConfig implements WebMvcConfigurer {

// @Override
// public void addCorsMappings(CorsRegistry registry) {
//  registry.addMapping("/**")  //允许所有访问地址
////          .allowedOrigins("http://localhost:9000","http://localhost:9000/login","http://192.168.4.2:9000","https://cdn.tailwindcss.com","https://cdnjs.cloudflare.com") //允许哪些服务器地址
//          .allowedOrigins("http://localhost:9000") //允许哪些服务器地址
//          .allowedMethods("*")   //允许的请求类型
//          .allowedHeaders("")   //允许所有的请求头
//          .allowCredentials(true)  //允许与凭据一起发送请求，Cookie可以跨域
//          .exposedHeaders("*");   //允许返回的头信息
// }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
     registry.addMapping("/**")  // 所有路径
             .allowedOrigins("http://localhost:9000","http://192.168.126.102:9000","http://localhost:9000/order/notify")
             .allowedMethods("GET", "POST", "PUT", "DELETE")
             .allowedHeaders("*")
             .allowCredentials(true)
             .maxAge(3600);
    }

     //图片的访问地址
     @Value("${portal.image-path}")
     private String imagePath;
     /**
      * 配置资源的访问地址
      */
     @Override
     public void addResourceHandlers(ResourceHandlerRegistry registry) {
       log.info("图片地址: {}", imagePath);
       registry.addResourceHandler("/book-mall/**").addResourceLocations(imagePath);
     }

    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Autowired
    private UrlProperties urlProperties;

    /**
     - 拦截器的配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //白名单从文件中读取
        List<String> whiteNames = urlProperties.getWhiteNames();
        log.info("白名单: {}", whiteNames);
        //要排除白名单
        registry.addInterceptor(jwtInterceptor).addPathPatterns("/**").excludePathPatterns(whiteNames);
    }
}